<?php

namespace app\controller\admin\cnf;

use app\bll\Datadict as BllDatadict;
use app\bll\OrganCompany as BllOrganCompany;
use app\bll\OrganPost as BllOrganPost;
use app\bll\User as BllUser;
use app\bll\UserTable as BllUserTable;
use core\controller\AdminBase;
use support\View;
use app\bll\UserField as BllUserField;

use Exception;

class User extends AdminBase
{
    public function index()
    {
        $bllUser = new BllUser();
        $users = $bllUser->paginator(
            username: request()->get('username', ''),
            phone: request()->get('phone', ''),
            email: request()->get('email', ''),
            organcompanyid: request()->get('organcompanyid', ''),
        );
        View::assign('users', $users);
        return $this->view();
    }

    /**
     * 获取用户更多信息
     *
     * @return mixed 返回视图
     */
    public function moreInfo()
    {
        // 创建 BllUser 类的实例，用于处理用户相关业务逻辑
        $bllUser         = new BllUser();
        // 创建 BllUserTable 类的实例，用于处理用户表相关业务逻辑
        $bllUserTable    = new BllUserTable();
        // 创建 BllUserField 类的实例，用于处理用户字段相关业务逻辑
        $BllUserField    = new BllUserField();
        // 创建 BllOrganCompany 类的实例，用于处理组织公司相关业务逻辑
        $bllOrganCompany = new BllOrganCompany();
        // 创建 BllOrganPost 类的实例，用于处理组织职位相关业务逻辑
        $bllOrganPost    = new BllOrganPost();
        // 获取所有职位信息
        $posts           = $bllOrganPost->select();
        // 以职位 ID 为键重新索引职位信息数组
        $posts           = array_column($posts, null, 'id');

        // 创建 BllDatadict 类的实例，用于处理数据字典相关业务逻辑
        $bllDatadict     = new BllDatadict();

        // 获取用户信息表信息
        $tables = $bllUserTable->selectInfoTable();
        // 遍历用户信息表
        foreach ($tables as $key => $table) {
            // 获取指定用户在当前表中的信息
            $tables[$key]['infomation'] = $bllUser->userInfomation(
                $table,
                request()->get('uid'),
            );
            // 如果当前表中没有用户信息，则跳过本次循环
            if (!$tables[$key]['infomation']) {
                continue;
            }

            // 获取当前表的字段信息
            $tables[$key]['fields'] = $BllUserField->select($table['name']);

            // 如果当前表是 frame_user_basicinfo 且存在组织公司 ID
            if ($table['name'] == 'frame_user_basicinfo' && $tables[$key]['infomation']['organcompanyid']) {
                // 获取该组织公司及其所有祖先公司信息
                $companys = $bllOrganCompany->getAncestorsAndSelf($tables[$key]['infomation']['organcompanyid']);
                $companytits = '';
                // 拼接公司名称
                foreach ($companys as $company) {
                    $companytits .= $company['title'] . ' / ';
                }
                // 将组织公司 ID 替换为拼接后的公司名称
                $tables[$key]['infomation']['organcompanyid'] = $companytits;
            }

            // 如果当前表是 frame_user_basicinfo 且存在组织职位 ID
            if ($table['name'] == 'frame_user_basicinfo' && $tables[$key]['infomation']['organpostid']) {
                // 将组织职位 ID 替换为对应的职位名称，如果不存在则为空字符串
                $tables[$key]['infomation']['organpostid'] = isset($posts[$tables[$key]['infomation']['organpostid']]) ?
                    $posts[$tables[$key]['infomation']['organpostid']]['title'] : '';
            }

            // 遍历当前表的字段信息
            foreach ($tables[$key]['fields'] as $fkey => $field) {
                // 如果字段的数据源类型为 1
                if ($field['sourcetype'] == 1) {
                    // 根据字段的数据源值查找数据字典信息
                    $dictinfo =  $bllDatadict->find($field['sourceval']);
                    // 以真实值为键重新索引数据字典值数组
                    $dictval = array_column($dictinfo['values'], null, 'realvalue');

                    // 如果当前表是多行模式
                    if ($table['multiline'] == 1) {
                        // 遍历当前表中的用户信息
                        foreach ($tables[$key]['infomation'] as $inf => $infomation) {
                            // 如果数据字典中存在对应的值，则将其替换为显示名称
                            if (isset($dictval[$tables[$key]['infomation'][$inf][$field['name']]])) {
                                $tables[$key]['infomation'][$inf][$field['name']] = $dictval[$tables[$key]['infomation'][$inf][$field['name']]]['displayname'];
                            }
                        }
                    } else {
                        // 如果数据字典中存在对应的值，则将其替换为显示名称
                        if (isset($dictval[$tables[$key]['infomation'][$field['name']]])) {
                            $tables[$key]['infomation'][$field['name']] = $dictval[$tables[$key]['infomation'][$field['name']]]['displayname'];
                        }
                    }
                }
            }
        }

        // 将职位信息分配给视图
        View::assign('posts', $posts);
        // 将处理后的用户信息表信息分配给视图
        View::assign('tables', $tables);
        // 返回视图，不包含框架
        return $this->view(frame: false);
    }


    /**
     * 禁用或解禁账号
     *
     * @return void
     */
    public function EnableDisable()
    {
        try {

            $bllUser = new BllUser();
            $bllUser->setStatus(
                request()->post('uid'),
                request()->post('status')
            );
        } catch (Exception $ex) {
            return $this->error($ex->getMessage());
        }
        return $this->success();
    }

    /**
     * 重置密码
     *
     * @return void
     */
    public function resetPwd()
    {
        $uid = request()->get('uid');
        $bllUser = new BllUser();
        if (request()->isPost()) {
            try {
                $bllUser->resetPwd(
                    $uid,
                    request()->post('pwd')
                );
            } catch (Exception $ex) {
                return $this->error($ex->getMessage());
            }
            return $this->success();
        } else {
            $userinfo = $bllUser->find($uid);
            View::assign('userinfo', $userinfo);
            return $this->view(frame: false);
        }
    }
}
